package com.atguigu.utils;

import com.alibaba.druid.pool.DruidAbstractDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.util.JdbcUtils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcUtil {
    private static DruidAbstractDataSource dataSource;

    static {
       try {
           Properties properties = new Properties();
           //读取jdbc.properties配置文件JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties")空指针用这个加载
           InputStream resourceAsStream = JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
           //从流中加载数据
           properties.load(resourceAsStream);
           //创建数据库连接池
           dataSource = (DruidAbstractDataSource) DruidDataSourceFactory.createDataSource(properties);
       } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /***
     * 获取数据库连接池中的连接
     * @return如果返回null,说明 获取失败
     */
    public static Connection getConnection(){
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return conn;
    }

    public static void closeConnection(Connection conn){
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {

    }
}
